package com.zhyl.zhyl_detect_demo;


import android.graphics.Bitmap;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.ViewTreeObserver;

import androidx.core.app.ActivityCompat;
import androidx.lifecycle.ViewModelProvider;

import com.zhyl.detectibrary.util.DetectItem;
import com.zhyl.detectibrary.util.DetectorListener;
import com.zhyl.detectibrary.util.ObjectDetectorHelper;
import com.zhyl.zhyl_detect_demo.databinding.ActivityMainBinding;
import com.zhyl.zhyl_detect_demo.utils.ImageUtils;
import com.zhyl.zhyl_detect_demo.utils.ThreadPoolManager;
import com.zhyl.zhyl_detect_demo.utils.camera.CameraHelper;
import com.zhyl.zhyl_detect_demo.utils.camera.CameraListener;
import com.zhyl.zhyl_detect_demo.viewmodel.MainViewModel;

import java.util.List;

public class MainActivity extends BaseActivity implements DetectorListener, ViewTreeObserver.OnGlobalLayoutListener {
    private static final String TAG = "MainActivity";
    private static final int ACTION_REQUEST_PERMISSIONS = 0x001;

    /**
     * 摄像头ID
     */
    private static final int SPECIFIC_CAMERA_ID = 0;

    private ActivityMainBinding binding;
    private MainViewModel viewModel;

    private CameraHelper cameraHelper;
    private boolean autoTakePictureFlag = true;
    private ObjectDetectorHelper objectDetectorHelper;
    private Integer imageHeight, imageWidth;

    /**
     * 所需的所有权限信息
     */
    private static final String[] NEEDED_PERMISSIONS = new String[]{
            android.Manifest.permission.CAMERA,
            android.Manifest.permission.ACCESS_NETWORK_STATE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_PHONE_STATE,
            android.Manifest.permission.INTERNET
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.getRoot().getViewTreeObserver().addOnGlobalLayoutListener(this);

        viewModel = new ViewModelProvider(this).get(MainViewModel.class);

        try {
            objectDetectorHelper = new ObjectDetectorHelper(this, this);
        }catch (Exception e){
            showToast(e.getMessage());
        }

        viewModel.getResults().observe(this,data->{
            if(cameraHelper==null){
                return;
            }

            // 显示检测框
            binding.objectReactView.setResults(data,
                    imageHeight,
                    imageWidth
            );
            binding.objectReactView.invalidate();

            binding.stableTv.setText("是否稳定:" + objectDetectorHelper.isImageDetectStable());
            binding.handTv.setText("检测到手:" + objectDetectorHelper.isDetectHand());

        });
        viewModel.getInferenceTime().observe(this,data->{
            binding.inferenceTimeTv.setText("检测时间:" + data.toString());

        });

    }
    @Override
    public void onGlobalLayout() {
        binding.dualCameraTexturePreviewRgb.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        if (!checkPermissions(NEEDED_PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);
        } else {
            initCamera(SPECIFIC_CAMERA_ID);
        }

    }

    /**
     * 初始化摄像头
     */
    private void initCamera(int cameraId) {
        CameraListener cameraListener = new CameraListener() {
            @Override
            public void onCameraOpened(Camera camera, int cameraId, int displayOrientation, boolean isMirror) {
                autoTakePictureDetect();
            }

            @Override
            public void onPreview(final byte[] nv21, Camera camera) {

            }

        };
        cameraHelper = new CameraHelper.Builder()
                .previewViewSize(new Point(binding.dualCameraTexturePreviewRgb.getMeasuredWidth(), binding.dualCameraTexturePreviewRgb.getMeasuredHeight()))
                .rotation(getWindowManager().getDefaultDisplay().getRotation())
                .specificCameraId(cameraId)
                .previewOn(binding.dualCameraTexturePreviewRgb)
                //.isMirror(true)
                .cameraListener(cameraListener)
                .build();
        cameraHelper.init();
        cameraHelper.start();
    }

    /**
     * 拍照识别
     */
    private void autoTakePictureDetect() {
        if(objectDetectorHelper==null){
            return;
        }
        ThreadPoolManager.executeSingle(() -> {
            while (autoTakePictureFlag) {
                cameraHelper.takePicture((byte[] nv21, int width, int height) ->{
                    Bitmap bitmap = ImageUtils.nv21ToBitmap(getApplicationContext(), nv21, width, height);
                    objectDetectorHelper.detect(bitmap, getWindowManager().getDefaultDisplay().getRotation());
                });
            }
        });

    }


    @Override
    public void onDetectorError(String error) {
        showToast("detect error:" + error);
    }

    @Override
    public void onDetectorResults(List<DetectItem> results, Long inferenceTime, Integer imageHeight, Integer imageWidth) {
        this.imageHeight  = imageHeight;
        this.imageWidth = imageWidth;
        viewModel.setResults(results);
        viewModel.setInferenceTime(inferenceTime);
    }

    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {
        if (requestCode == ACTION_REQUEST_PERMISSIONS) {
            if (isAllGranted) {
                initCamera(SPECIFIC_CAMERA_ID);
            } else {
                showToast("permission_denied");
            }
        }
    }
}


